import { ref } from 'vue';

import { deserialize } from '@/plugins/reflect-metadata';
import type { ListState } from '@/types';

import { getTransactionList, getUserTotalFlow } from '../api';
import { TransactionQueryType } from '../const';
import type TransactionItem from '../models/TransactionItem';
import TransactionList, { TransactionFlowTotal, TransactionQuery } from '../models/TransactionList';

const useTransaction = () => {
  const params = ref<TransactionQuery>(new TransactionQuery());
  const pageState = ref({
    finished: false,
    refreshing: false,
    error: false,
  });
  const state = ref<ListState<TransactionItem>>({
    data: [],
    loading: false,
    total: 0,
  });

  const fetchData = async () => {
    try {
      if (pageState.value.refreshing) {
        state.value.data = [];
        pageState.value.refreshing = false;
      }
      pageState.value.error = false;
      state.value.loading = true;
      const { data } = await getTransactionList(params.value);
      const resultData = deserialize(data, TransactionList);
      state.value.data.push(...resultData.items);
      state.value.total = resultData.total;
      if (params.value.status !== TransactionQueryType.全部类型) {
        state.value.data = state.value.data
          .filter((item) => item.transactionType === params.value.status);
        state.value.total = state.value.data.length;
      }
    } catch {
      pageState.value.error = true;
    } finally {
      state.value.loading = false;
      if (state.value.data.length >= state.value.total) {
        pageState.value.finished = true;
      } else {
        params.value.pageNum += 1;
      }
    }
  };

  const refresh = async () => {
    pageState.value.finished = false;
    params.value.pageNum = 1;
    fetchData();
  };

  const userFlow = ref<{ data: TransactionFlowTotal, loading: boolean }>({
    data: new TransactionFlowTotal(),
    loading: false,
  });
  const fetchSummary = async () => {
    try {
      userFlow.value.loading = true;
      const { data } = await getUserTotalFlow();
      const resultData = deserialize(data.data, TransactionFlowTotal);
      userFlow.value.data = resultData;
    } catch (error) {
      //
    } finally {
      userFlow.value.loading = false;
    }
  };

  return {
    params,
    pageState,
    state,
    userFlow,
    fetchData,
    refresh,
    fetchSummary,
  };
};

export default useTransaction;
